<template>
    <div>
        <ZWDrawer ref="zwRef" @submit="save" @close="close" @cancel="cancel">
            <div class="contents">
                <div v-if="drawerData.controlType === 'create'" class="toggleType">
                    <div class="toggleBtn" @click="toggleType">
                        <el-icon>
                            <Switch />
                        </el-icon>
                        切换客户类型
                    </div>
                </div>

                <el-form ref="ruleFormRef" :model="form" label-width="auto">
                    <div class="form-title">客户信息</div>
                    <el-form-item label="客户公海" required :label-width="labelWidth">
                        <el-select
                            v-model="form.cust_seas_id"
                            placeholder="请选择客户公海"
                            :disabled="drawerData.controlType == 'look'">
                            <el-option v-for="item in seaids" :key="item.id" :value="item.id" :label="item.name">
                                {{ item.name }}
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item
                        v-for="(item, index) in customAttr"
                        :key="index"
                        :label="item.attr_name"
                        :required="item.is_required == 2"
                        :label-width="labelWidth">
                        <el-input
                            v-if="item.attr_type == 'textbox'"
                            v-model="item.current_val"
                            :placeholder="'请输入' + item.attr_name"
                            :disabled="drawerData.controlType == 'look'" />
                        <!--  手机号 -->
                        <el-input
                            v-if="item.attr_type == 'mobile'"
                            v-model="item.current_val"
                            :placeholder="'请输入' + item.attr_name"
                            show-word-limit
                            maxlength="11"
                            indeterminate
                            :disabled="drawerData.controlType == 'look' || !!item.isDisabled"
                            @blur="valiateMobile(index, false, item.is_required)" />
                        <!-- 备用手机号 -->
                        <el-input
                            v-if="item.attr_type == 'remark_mobile'"
                            v-model="item.current_val"
                            show-word-limit
                            maxlength="11"
                            indeterminate
                            :placeholder="'请输入' + item.attr_name"
                            :disabled="drawerData.controlType == 'look' || !!item.isDisabled"
                            @blur="valiateMobile(index, false, item.is_required)" />

                        <el-input
                            v-if="item.attr_type == 'email'"
                            v-model="item.current_val"
                            :disabled="drawerData.controlType == 'look'"
                            :show-word-limit="!!item.max_length"
                            :maxlength="item.max_length || ''"
                            :placeholder="`请输入${item.attr_name}`" />
                        <el-input
                            v-if="item.attr_type == 'textarea'"
                            v-model="item.current_val"
                            type="textarea"
                            :disabled="drawerData.controlType == 'look'"
                            :placeholder="`请输入${item.attr_name}`" />
                        <el-checkbox-group
                            v-if="item.attr_type == 'muti_select'"
                            v-model="item.current_val"
                            :disabled="drawerData.controlType == 'look'">
                            <el-checkbox v-for="items in item.attr_val" :key="items.key" :label="items.key">
                                {{ items.val }}
                            </el-checkbox>
                        </el-checkbox-group>
                        <el-select
                            v-if="item.attr_type == 'select'"
                            v-model="item.current_val"
                            :placeholder="'请选择' + item.attr_name"
                            :disabled="drawerData.controlType == 'look'">
                            <el-option
                                v-for="items in item.attr_val"
                                :key="items.key"
                                :value="items.key"
                                :label="items.val">
                                {{ items.val }}
                            </el-option>
                        </el-select>

                        <CascaderItem
                            v-if="item.attr_type == 'pca'"
                            :item-value="item"
                            :is-disabled="drawerData.controlType" />

                        <!-- 生日 -->
                        <el-date-picker
                            v-if="item.attr_type == 'date' && item.system_code == 'birthday'"
                            v-model="item.current_val"
                            type="date"
                            style="width: 100%"
                            value-format="YYYY-MM-DD"
                            :disabled="drawerData.controlType == 'look'"
                            :disabled-date="endDateOpt"
                            :placeholder="`请输入${item.attr_name}`">
                        </el-date-picker>
                        <!-- 非生日 -->
                        <el-date-picker
                            v-if="item.attr_type == 'date' && item.system_code != 'birthday'"
                            v-model="item.current_val"
                            type="date"
                            style="width: 100%"
                            value-format="YYYY-MM-DD"
                            :disabled="drawerData.controlType == 'look'"
                            :placeholder="`请输入${item.attr_name}`">
                        </el-date-picker>

                        <div
                            v-if="item.attr_type == 'picture'"
                            :class="`upload-content ${drawerData.controlType == 'look' ? 'noEdit' : ''}`">
                            <el-upload
                                v-if="!item.current_val"
                                action="none"
                                accept=".jpg,.jpeg,.png,.JPG,.JPEG,.pdf"
                                :on-change="beforeAvatarUpload"
                                :show-file-list="false"
                                :limit="1"
                                :auto-upload="false"
                                :disabled="drawerData.controlType == 'look'"
                                @click="getUploadKey(index, false)">
                                <div class="upload-box">
                                    <img src="@/assets/image/content/add-icon.png" alt="" />
                                    <div>点击上传</div>
                                </div>
                            </el-upload>
                            <div v-else-if="item.current_val.includes('.pdf')" class="upload-file-pdf">
                                <div class="text">PDF</div>
                                <el-icon class="del" @click="delFile(index, false)">
                                    <Delete />
                                </el-icon>
                            </div>
                            <div v-else class="upload-file-box">
                                <el-image style="width: 100%; height: 100%" :src="item.current_val" fit="cover" />
                                <el-icon class="del" @click="delFile(index, false)">
                                    <Delete />
                                </el-icon>
                            </div>
                            <div class="tips">支持jpg、png、jpeg、pdf，大小不超过10M</div>
                        </div>
                    </el-form-item>

                    <el-form-item label="客户阶段" required :label-width="labelWidth">
                        <el-select
                            v-model="form.cust_stage_id"
                            placeholder="请选择客户阶段"
                            :disabled="drawerData.controlType == 'look'">
                            <el-option v-for="item in levelid" :key="item.id" :value="item.id" :label="item.name">
                                {{ item.name }}
                            </el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item label="所属员工" required :label-width="labelWidth">
                        <select-depart
                            v-model="form.belong_work_user_id"
                            :creators="form.belong_work_user_id_creators"
                            :multiple="false"
                            :disabled="drawerData.controlType == 'look'" />
                    </el-form-item>

                    <!-- <el-form-item label="协助员工" :label-width="labelWidth">
            <select-depart v-model="form.assist_ids" :creators="form.assist_ids_creators" multiple @change="changeAssist" :disabled="drawerData.controlType == 'look'" />
          </el-form-item> -->
                </el-form>

                <!-- <div class="form-title">联系人信息</div>
        <div class="contact-item" v-for="(item, index) in contactsForms">
          <div class="title">
            <span>联系人{{ index + 1 }}</span>
            <el-icon class="del" :class="{ look: drawerData.controlType == 'look' }" :size="size" :color="color" v-if="contactsForms.length > 1 && index > 0" @click="deleteContact(item, index)">
              <Delete />
            </el-icon>
          </div>
          <el-form :model="item" label-width="auto">
            <el-form-item label="姓名" required>
              <el-input v-model="item.name" :disabled="drawerData.controlType == 'look'" />
            </el-form-item>
            <el-form-item label="手机号" required>
              <el-input v-model="item.mobile" show-word-limit maxlength="11" :disabled="drawerData.controlType == 'look'" />
            </el-form-item>
          </el-form>
        </div>
        <div class="add-contact" v-if="drawerData.controlType !== 'look'" @click="addContact">添加联系人</div> -->
            </div>
        </ZWDrawer>

        <!-- <Dialog :appDialog="appDialogApply">
      <div class="dialog_content">该企业已存在，申请成为协助人？</div>
    </Dialog> -->

        <!-- <ZWDepart ref="DepartRef" @submit="getDepart" type="1" /> -->
    </div>
</template>
<script lang="ts" setup>
import { getTaxNumber } from '@/api/common';
import { ref, reactive, watch, onMounted, onBeforeUnmount, getCurrentInstance, ComponentInternalInstance } from 'vue';
import { ElForm, ElMessage, ElMessageBox, UploadProps, FormRules } from 'element-plus';
import ZWDrawer from '@/components/ZWDrawer.vue';
import ZWDepart from '@/components/ZWDepart.vue';
import Dialog from '@/components/Dialog.vue';

import CascaderItem from './CascaderItem.vue';

import selectDepart from './selectDepart.vue';
import { getClubSource } from '@/api/customer/clubManage/commonSea';
import { stageList } from '@/view/customer/manage/configure/api';
import {
    seaList,
    applyCompanyHelper,
    getPersonCustomerForm,
    getCompanyCustomerDetail,
    addCompanyCustomer,
    aditCompanyCustomer,
    lastRecord
} from '@/api/customerCenter/customerSea';
import { createCustomer, baseUpdate, getAttrList, customerShow } from '@/api/customerCenter';
import { getCustomerOpenseaSelect } from '@/api/customer/manage/list';

import { uploadFile2 } from '@/api/common';
import { getSetionId } from '@/utils/utils';
import { deepCopy } from '@/utils/helper';

import { validateEmail, validateIdCard } from '@/utils/validate';

import CityJson from '@/assets/js/city';

const labelWidth = ref<number>(140);

const systemAttrList: any = [
    { attr_name: '姓名', attr_type: 'input', attr_val: [], code: 'name', key: 'name' },
    {
        attr_name: '手机号',
        attr_type: 'input',
        attr_val: [],
        code: 'mobile',
        key: 'mobile'
    },
    { attr_name: '性别', attr_type: 'select', attr_val: [], code: 'sex', key: 'sex' },
    {
        attr_name: '生日',
        attr_type: 'date',
        attr_val: '',
        code: 'birthday',
        key: 'birthday'
    },
    { attr_name: '年龄', attr_type: 'input', attr_val: [], code: 'age', key: 'age' },
    { attr_name: '备注', attr_type: 'input', attr_val: [], code: 'remark', key: 'remark' },
    { attr_name: '邮箱', attr_type: 'input', attr_val: [], code: 'email', key: 'email' },
    {
        attr_name: '学历',
        attr_type: 'select',
        attr_val: [],
        code: 'education',
        key: 'education'
    },
    {
        attr_name: '地址',
        attr_type: 'input',
        attr_val: [],
        code: 'address',
        key: 'address'
    },
    {
        attr_name: '微信号',
        attr_type: 'input',
        attr_val: [],
        code: 'wx_number',
        key: 'wx_number'
    },
    {
        attr_name: '头像',
        attr_type: 'picture',
        attr_val: [],
        code: 'avatar',
        key: 'avatar'
    },
    {
        attr_name: 'QQ',
        attr_type: 'input',
        attr_val: [],
        code: 'qq_number',
        key: 'qq_number'
    },
    {
        attr_name: '公司',
        attr_type: 'input',
        attr_val: [],
        code: 'company',
        key: 'company'
    },
    {
        attr_name: '年收入',
        attr_type: 'select',
        attr_val: [],
        code: 'income',
        key: 'income'
    },
    { attr_name: '区域', attr_type: 'input', attr_val: [], code: 'region', key: 'region' },
    { attr_name: '爱好', attr_type: 'input', attr_val: [], code: 'hobby', key: 'hobby' },
    {
        attr_name: '行业',
        attr_type: 'input',
        attr_val: [],
        code: 'industry',
        key: 'industry'
    },
    {
        attr_name: '客户来源',
        attr_type: 'select',
        attr_val: [],
        code: 'source',
        key: 'source_id'
    }
];

const cityProps = reactive<any>({
    value: 'code',
    label: 'name'
});

type FormInstance = InstanceType<typeof ElForm>;
const ruleFormRef: any = ref<FormInstance>();

const { appContext } = getCurrentInstance() as ComponentInternalInstance;
const globalProperties = ref(appContext.config.globalProperties);

// const {
//     appContext: {
//         config: { globalProperties }
//     }
// } = <ComponentInternalInstance>getCurrentInstance();

type Props = {
    modelValue: boolean;
    row_id: string;
    sourceArr: [];
};
const props = defineProps<Props>();
const emit = defineEmits(['close', 'submit', 'update:modelValue']);
const updateVisible = (flag: boolean): void => {
    emit('update:modelValue', flag);
};

const endDateOpt = (date: Date): boolean => {
    const now = new Date().getTime();
    return date.getTime() > now;
};

const drawerData = ref({
    title: '添加个人客户',
    direction: 'rtl',
    userInfo: {},
    controlType: 'create',
    seas_id: ''
});

const cust_id = ref<any>(0);

// const changeCity = (val: any) => {
//   if(val){
//     let vals = getCascaderObj(val, CityJson);
//     console.log(vals);
//   }
//   // let vals = getCascaderObj(val, CityJson);
//   // console.log(vals);
//   // console.log(cascaderRef.value.checkedValue, "------vals");
// };
// const getCascaderObj = (val, opt) => {
//   return val.map(function (value, index, array) {
//     for (var itm of opt) {
//       if (itm.code == value) {
//         opt = itm.children;
//         return itm;
//       }
//     }
//     return null;
//   });
// };
const cancelHandel = () => {
    appDialogApply.visible = false;
};
const submitHandel = () => {
    applyCompanyHelper({ cust_id: cust_id.value }).then((res: any) => {
        appDialogApply.visible = false;
        zwRef.value.drawer = false;
        emit('submit');
    });
};
const appDialogApply = reactive({
    visible: false,
    title: '申请协助人',
    width: '500px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '申请协助人'
});

const zwRef = ref(null);
const DepartRef = ref(null);
const creators = ref([]);
const form = reactive({
    cust_seas_id: 0,
    cust_stage_id: '',
    belong_work_user_id: [],
    // assist_ids: [],
    belong_work_user_id_creators: []
    // assist_ids_creators: []
});

const contactsForms = reactive<any>([]);

const del_contacts_info = reactive<any>([]);

const imgProps = ref([]); // 自定义图片prop

const contactsFormRules = reactive<FormRules>({
    name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
    mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
});
const getLastRecord = () => {
    lastRecord({ type: 1 }).then((res: any) => {
        form.cust_seas_id = res.type_id != 0 ? res.type_id : '';
    });
};
const customCropAttr = reactive<any>([]);
const customAttr = reactive<any>([]);
// 获取企业税号
// let timer: any = null
const taxNuIndex = ref(-1); // 是否开启企业税号
const onGettaxNu = (v: any, type: any) => {
    if (type == 'corp_name' && v && taxNuIndex.value != -1) {
        getTaxNumber({ keyword: v })
            .then((res: any) => {
                // customCropAttr[taxNuIndex.value].current_val = res.credit_code
                if (!res.credit_code) {
                    ElMessage.warning('未匹配到企业');
                }
            })
            .catch((err: any) => {
                // customCropAttr[taxNuIndex.value].current_val = ''
            });
    }
};
const getDetail = () => {
    if (drawerData.value.controlType === 'create') {
        getPersonCustomerForm({}).then((res: any) => {
            const { custom_attr, stage_id } = res;

            // form.cust_stage_id = stage_id
            // customCropAttr.splice(0)
            customAttr.splice(0);

            let ind = 0;
            const trans = custom_attr.find((item: any, index: number) => {
                if (item.attr_name == '客户来源') {
                    ind = index;
                    return true;
                } else {
                    return false;
                }
            });
            if (trans) {
                const arr = props.sourceArr.map((it: any) => ({
                    ...it,
                    key: it.id || '',
                    val: it.name || ''
                }));
                arr.shift();
                trans.attr_val = arr;
                trans.current_val = trans.current_val || '';
                custom_attr.splice(ind, 1, trans);
            }
            // customCropAttr.push(...custom_crop_attr)
            customAttr.push(...custom_attr);
            customAttr.forEach(item => {
                const rex = /^[1][3-9][0-9]{9}$/;
                if (item.attr_type == 'mobile' && rex.test(item.current_val)) {
                    item.isDisabled = true;
                }
            });
            initSelectDefaultVal();
        });
    } else {
        getPersonCustomerForm({ cust_id: drawerData.value.userInfo.id }).then(res => {
            for (const key in res) {
                if (key != 'custom_attr') {
                    form[key] = res[key];
                }
            }

            const { custom_attr, stage_id, belong_work_user_id: belong_work_user_id = [] } = res;

            form.cust_stage_id = stage_id;

            if (belong_work_user_id?.length) {
                form.belong_work_user_id = belong_work_user_id?.map(ite => ite.id);
                form.belong_work_user_id_creators = belong_work_user_id;
            }
            let ind = 0;
            const trans = custom_attr.find((item: any, index: number) => {
                if (item.attr_name == '客户来源') {
                    ind = index;
                    return true;
                } else {
                    return false;
                }
            });
            if (trans) {
                trans.current_val = Number(trans.current_val);
                const arr = props.sourceArr.map((it: any) => ({
                    ...it,
                    key: it.id || '',
                    val: it.name || ''
                }));
                arr.shift();
                trans.attr_val = arr;
                custom_attr.splice(ind, 1, trans);
            }
            // customCropAttr.splice(0)
            customAttr.splice(0);
            // customCropAttr.push(...custom_crop_attr)
            customAttr.push(...custom_attr);
            // customCropAttr.forEach((item) => {
            //   if (item.attr_type == 'muti_select' && !item.current_val) {
            //     item.current_val = []
            //   }
            // })
            customAttr.forEach(item => {
                const rex = /^[1][3-9][0-9]{9}$/;
                if (item.attr_type == 'mobile' && rex.test(item.current_val)) {
                    item.isDisabled = true;
                }
                if (item.attr_type == 'muti_select' && !item.current_val) {
                    item.current_val = [];
                }

                if (item.attr_type == 'date' && item.system_code == 'birthday' && item.current_val == '0000-00-00') {
                    item.current_val = '';
                }

                if (item.attr_type == 'select' && item.system_code == 'sex') {
                    item.current_val = '' + item.current_val || '';
                }
                if (item.attr_type == 'pca') {
                    if (item.current_val) {
                        item.attr_val = [
                            item.current_val.province_code.toString(),
                            item.current_val.city_code.toString(),
                            item.current_val?.area_code?.toString()
                        ];
                        if (item.attr_val[2] == 0) {
                            item.attr_val.pop();
                        }
                    } else {
                        return;
                    }
                }
            });
        });
    }
};
const seaids = reactive<any>([]); //公海列表
const levelid = reactive<any>([]); //客户等级列表
const sourceid = ref([]); //客户来源

// 切换客户类型
const toggleType = () => {
    updateVisible(false);
    globalProperties.value.$bus.emit('openAddCustomerSelect');
};

//获取客户公海列表
const getSeaList = () => {
    seaids.splice(0);
    getCustomerOpenseaSelect({ type: 1 }).then((res: any) => {
        seaids.push(...res);
    });
};
//获取客户等级
const getLevelList = () => {
    levelid.splice(0);
    stageList({ page: 1, page_size: 99 }).then((res: any) => {
        levelid.push(...res);
    });
};
//获取客户来源
const getSourceList = () => {
    sourceid.value = [];
    getClubSource({ page: 1, page_size: 99 }).then((res: any) => {
        res.data.forEach(item => {
            if (item.status == 1) {
                sourceid.value.push(item);
            }
        });
    });
};

let nowUploadIndex = 0;
let nowUploadFlag = false;
const getUploadKey = (index: number, flag: boolean) => {
    nowUploadIndex = index;
    nowUploadFlag = flag;
};

// 上传图片的方法
const uploadFun = (file: any, fileName: string, key: string) => {
    uploadFile2({
        file,
        fileName
    }).then((r: any) => {
        if (nowUploadFlag) {
            // customCropAttr[nowUploadIndex].current_val = r.url
            // console.log(formData.value[nowUploadKey])
            // 验证图片上传
            if (imgProps.value.length > 0) {
                imgProps.value.forEach(item => {
                    ruleFormRef.value.validateField([item]);
                });
            }
        } else {
            customAttr[nowUploadIndex].current_val = r.url;
            // console.log(formData.value[nowUploadKey])
            // 验证图片上传
            if (imgProps.value.length > 0) {
                imgProps.value.forEach(item => {
                    ruleFormRef.value.validateField([item]);
                });
            }
        }
    });
};
// 上传检验
const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile: any, key: string) => {
    if (!rawFile) {
        return;
    }
    if (rawFile.size / 1024 / 1024 > 10) {
        ElMessage.error('上传图片大小不能超过10M');
        return false;
    }
    uploadFun(rawFile.raw, rawFile.name, key);
};

//
const delFile = (index: number, flag: boolean) => {
    if (flag) {
        // customCropAttr[index].current_val = ''
    } else {
        customAttr[index].current_val = '';
    }
};

const valiateMobile = (index: number, flag: boolean) => {
    const rex = /^[1][3-9][0-9]{9}$/;
    const current_val = customAttr[index].current_val;
    if (!rex.test(current_val)) {
        ElMessage.warning('请输入合法的手机号');
        return false;
    } else {
        return true;
    }
};
const valiateid = (index: number, flag: boolean, required?: number) => {
    const rex = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{16,}$/;
    const attrs = customAttr[index];
    if (attrs.attr_name != '姓名' && required == 2) {
        if (!rex.test(attrs.current_val)) {
            ElMessage.warning(attrs.attr_name + '必须包含数字字母并且长度不能小于16位');
            return false;
        } else {
            return true;
        }
    } else {
        return true;
    }
};

// const valiateContactsForms = (): void => {
//   let rex = /^[1][3-9][0-9]{9}$/
//   return contactsForms.some((item) => rex.test(item.mobile))
// }

const save = () => {
    // const validateCustomCropAttr = validateFun(customCropAttr, true)
    const validateCustomCropAttr = true;
    if (validateCustomCropAttr) {
        const validateCustomAttr = validateFun(customAttr, false);
        if (validateCustomAttr && validateCustomForm()) {
            // if (contactsForms.length) {
            //   if (contactsForms.some((item) => !item.name || !item.mobile)) {
            //     ElMessage.warning('请完善联系人信息')
            //     return
            //   } else if (!valiateContactsForms()) {
            //     ElMessage.warning('联系人手机号码有误')
            //     return
            //   }
            // }
            let params = {};
            // systemAttrList.forEach((item: any) => {
            //   if(form[item.key]){
            //     params.system_attr[item.key] = form[item.key]
            //   }
            // })
            const custom_attr = validateCustomAttr.filter(item => {
                if (item.is_system != 1) {
                    item.attr_val = item.current_val;
                    return true;
                } else {
                    return false;
                }
            });
            custom_attr.forEach(item => {
                item.attr_val = item.current_val;
            });

            const system_attr = validateCustomAttr
                .filter(ite => ite.is_system == 1)
                .reduce((pre, item) => {
                    const { system_code, current_val } = item;
                    pre[system_code] = current_val;
                    return pre;
                }, {});
            if (drawerData.value.controlType === 'create') {
                const mobile = validateCustomAttr.find(item => item.attr_name == '手机号')?.current_val || '';
                // const corp_name = validateCustomCropAttr.find((item) => item.attr_name == '企业全称')?.current_val || ''
                const source_id = validateCustomAttr.find(item => item.attr_name == '客户来源')?.current_val || '';
                const extraForm = { mobile, source_id };
                const { belong_work_user_id: belong_work_user_id = [] } = form;
                params = {
                    ...form,
                    ...extraForm,
                    belong_work_user_id: belong_work_user_id[0],
                    custom_attr,
                    system_attr
                };
                createCustomer(params).then((res: any) => {
                    ElMessage.success('保存成功');
                    zwRef.value.drawer = false;
                    emit('submit');
                });
            } else if (drawerData.value.controlType === 'edit') {
                const mobile = validateCustomAttr.find(item => item.attr_name == '手机号')?.current_val || '';
                // const corp_name = validateCustomCropAttr.find((item) => item.attr_name == '企业全称')?.current_val || ''
                const source_id = validateCustomAttr.find(item => item.attr_name == '客户来源')?.current_val || '';
                const extraForm = { mobile, source_id };
                const { belong_work_user_id: belong_work_user_id = [] } = form;
                params = {
                    ...form,
                    ...extraForm,
                    belong_work_user_id: belong_work_user_id[0],
                    custom_attr,
                    cust_id: drawerData.value.userInfo.id,
                    system_attr
                };
                baseUpdate(params).then(res => {
                    ElMessage.success('编辑成功');
                    zwRef.value.drawer = false;
                    emit('submit');
                });
            }
        }
    }
};

const validateFun = (data: any, flag: boolean) => {
    if (!flag) {
    }
    try {
        data.forEach((item: any, index: number) => {
            if (!item.current_val && item.is_required == 2 && item.attr_type != 'muti_select') {
                ElMessage.warning(item.attr_name + '不能为空');
                throw new Error();
            } else if (item.attr_type == 'muti_select' && item.is_required == 2 && !item.current_val.length) {
                ElMessage.warning(item.attr_name + '不能为空');
                throw new Error();
            } else if (item.system_code == 'idcard' && item.current_val) {
                if (!validateIdCard(item.current_val)) {
                    ElMessage.warning(item.attr_name + '格式不正确');
                    throw new Error();
                }
            } else if (item.system_code == 'email' && item.current_val) {
                if (!validateEmail(item.current_val)) {
                    ElMessage.warning(item.attr_name + '格式不正确');
                    throw new Error();
                }
            }
        });
    } catch (e) {
        return false;
    }
    try {
        data.forEach((items: any, indexs: number) => {
            if (items.is_required == 2 && items.attr_type == 'mobile') {
                const flag2 = valiateMobile(indexs, flag);
                if (!flag2) {
                    throw new Error();
                }
            } else if (items.is_required == 2 && items.attr_name != '姓名') {
                // let flag = valiateid(indexs, flag, 2)
                // if (!flag) {
                //   throw new Error()
                // }
            }
        });
    } catch (e) {
        return false;
    }
    // data.forEach((item) => {
    //   delete item.attr_val
    //   delete item.is_required
    //   delete item.system_code
    // })

    return data;
};

const validateCustomForm = (): boolean => {
    if (!form.cust_seas_id) {
        ElMessage.warning('请选择公海');
        return false;
    } else if (!form.cust_stage_id) {
        ElMessage.warning('请选择客户阶段');
        return false;
    } else if (!form.belong_work_user_id.length) {
        ElMessage.warning('请选择归属员工');
        return false;
    } else {
        return true;
    }
};

const cancel = () => {
    for (const key in form) {
        if (key != 'custom_attr' && key != 'cust_seas_id') {
            form[key] = '';
        }
        initSelectDefaultVal();
    }
};
//数据
const initSelectDefaultVal = () => {
    // customCropAttr.forEach((item: any) => {
    //   if (item.attr_type == 'muti_select') {
    //     item.current_val = []
    //   } else {
    //     item.current_val = ''
    //   }
    // })
    customAttr.forEach((item: any) => {
        if (item.attr_type == 'muti_select') {
            item.current_val = [];
        } else {
            item.current_val = '';
        }
    });
    // contactsForms.forEach((item: any) => {
    //   item.name = ''
    //   item.mobile = ''
    // })
    form.belong_work_user_id = [];
    // form.assist_ids = []
    form.belong_work_user_id_creators = [];
    // form.assist_ids_creators = []
};

// const addContact = (): void => {
//   if (contactsForms.length < 5) {
//     const formItem: any = {
//       name: '',
//       mobile: ''
//     }
//     contactsForms.push(formItem)
//   } else {
//     ElMessage.warning('最多新建5个联系人')
//   }
// }

// const deleteContact = (item: any, index: number): void => {
//   if (drawerData.value.controlType !== 'look') {
//     if (contactsForms.length > 1) {
//       ElMessageBox.confirm('确定删除该联系人吗？', '注意！', {
//         confirmButtonText: '确定',
//         cancelButtonText: '取消',
//         type: 'warning'
//       }).then(() => {
//         if (item.id) {
//           del_contacts_info.push(item)
//         }
//         contactsForms.splice(index, 1)
//       })
//     }
//   }
// }

const close = () => {
    // contactsForms.splice(0)
    // addContact()
    emit('close');
};
watch(
    () => props.modelValue,
    val => {
        if (val) {
            form.cust_seas_id = drawerData.value.seas_id;
            form.cust_stage_id = '';
            form.belong_work_user_id = [];
            // form.assist_ids = []
            form.belong_work_user_id_creators = [];
            // form.assist_ids_creators = []
            zwRef.value.resetMsg = '重置';
            zwRef.value.drawerMsg = '保存';
            zwRef.value.isResetShow = true;
            if (drawerData.value.controlType === 'edit') {
                zwRef.value.isResetShow = false;
                zwRef.value.isShow = true;
                zwRef.value.title = '编辑个人客户';
            } else if (drawerData.value.controlType === 'look') {
                zwRef.value.isResetShow = false;
                zwRef.value.isShow = false;
                zwRef.value.title = '查看个人客户';
            } else {
                zwRef.value.title = '添加个人客户';
            }
            getDetail();
            getSourceList();
            getLevelList();
            getSeaList();
            getLastRecord();
            zwRef.value.drawer = true;
            zwRef.value.width = '600px';
        } else {
            cancel();
            zwRef.value.drawer = false;
        }
    }
);

onMounted(() => {
    globalProperties.value.$bus.on('openAddCustomerCompany', () => {
        updateVisible(true);
    });
});
onBeforeUnmount(() => {
    globalProperties.value.$bus.off('openAddCustomerCompany');
});

defineExpose({
    drawerData
});
</script>
<style scoped lang="scss">
.contents {
    padding-bottom: 10px;

    .toggleType {
        margin-bottom: 6px;
        display: flex;
        justify-content: flex-end;
        align-items: center;

        .toggleBtn {
            font-size: 12px;
            color: #ff6b00;

            &:hover {
                cursor: pointer;
                color: #ffa046;
            }
        }
    }

    .form-title {
        height: 18px;
        line-height: 18px;
        font-weight: 700;
        border-left: 4px solid #ff6b00;
        padding-left: 6px;
        margin: 8px 0 24px;
    }

    .contact-item {
        border: 1px solid #eee;
        margin-bottom: 10px;
        padding: 10px 20px;
        box-sizing: border-box;

        .title {
            margin: 10px 0 16px;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .del {
                color: #ff6b00;

                &:hover {
                    cursor: pointer;
                }
            }
            .look {
                color: #eee;
                cursor: not-allowed;
            }
        }
    }

    .add-contact {
        display: inline-block;
        margin-top: 10px;
        margin-bottom: 20px;
        line-height: 1;
        padding: 6px 24px;
        border-radius: 4px;
        color: #ff6b00;
        border: 1px solid #ff6b00;

        &:hover {
            cursor: pointer;
            background-color: #ff6b00;
            color: #fff;
        }
    }

    .el-form {
        .el-form-item {
            .el-select {
                width: 100%;
            }
            .staffs_item {
                margin-right: 6px;
            }
        }

        .upload-content {
            display: flex;
            align-items: flex-end;
            .tips {
                text-indent: 6px;
                font-size: 12px;
                color: #888;
                line-height: 1.8;
            }
            &.noEdit {
                pointer-events: none !important;

                .upload-box {
                    background: lightgray;
                    position: relative;

                    &::after {
                        content: '';
                        width: 100%;
                        height: 100%;
                        background: lightgray;
                        opacity: 0.6;
                        position: absolute;
                        top: 0;
                        left: 0;
                    }
                }
            }

            .upload-box {
                width: 110px;
                height: 110px;
                text-align: center;
                border-radius: 4px;
                background: #f8f8f8;
                border: 1px solid #eaeaea;
                box-sizing: border-box;
                padding-top: 28px;

                img {
                    width: 20px;
                    height: 20px;
                }

                div {
                    width: 100%;
                    line-height: 14px;
                    font-size: 14px;
                    font-family: STHeitiSC-Light, STHeitiSC;
                    color: #ff6b00;
                }
            }
            .upload-file-pdf {
                position: relative;
                width: 110px;
                height: 110px;
                border-radius: 4px;
                border: 1px solid #eaeaea;
                background-color: blue;
                overflow: hidden;
                .text {
                    width: 110px;
                    line-height: 110px;
                    text-align: center;
                    font-size: 18px;
                    font-weight: 600;
                    color: #fff;
                }
                .del {
                    position: absolute;
                    width: 26px;
                    height: 26px;
                    font-size: 18px;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background-color: #bbb;
                    top: 5px;
                    right: 5px;
                    color: #fff;
                    &:hover {
                        cursor: pointer;
                        background-color: #ccc;
                    }
                }
            }
            .upload-file-box {
                position: relative;
                width: 110px;
                height: 110px;
                border-radius: 4px;
                border: 1px solid #eaeaea;
                overflow: hidden;
                .del {
                    position: absolute;
                    width: 26px;
                    height: 26px;
                    font-size: 18px;
                    border-radius: 50%;
                    display: flex;
                    align-items: center;
                    justify-content: center;
                    background-color: #bbb;
                    top: 5px;
                    right: 5px;
                    color: #fff;
                    &:hover {
                        cursor: pointer;
                        background-color: #ccc;
                    }
                }
            }

            .upload-desc {
                font-size: 14px;
                font-family: STHeitiSC-Light, STHeitiSC;
                font-weight: 300;
                color: #969696;
                padding-top: 10px;
                span {
                    color: #ff6b00;
                    cursor: pointer;
                }
            }
        }
    }
}
</style>
